﻿using Prism.Commands;
using Prism.Mvvm;
using Prism.Services.Dialogs;
using samrtind;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace OpticalWheelPlasticFilmTest.ViewModels.Dialogs
{
    public class IODialogViewModel : BindableBase, IDialogAware
    {
        bool runFlag;
        IntPtr hMotion;
        public string Title { get; set; } = "IO";
        private ObservableCollection<bool> iN = new ObservableCollection<bool>();
        public ObservableCollection<bool> IN
        {
            get { return iN; }
            set { SetProperty(ref iN, value); }
        }
        private ObservableCollection<bool> oUT = new ObservableCollection<bool>();
        public ObservableCollection<bool> OUT
        {
            get { return oUT; }
            set { SetProperty(ref oUT, value); }
        }
        private DelegateCommand<object> outActionCommand;
        public DelegateCommand<object> OutActionCommand =>
            outActionCommand ?? (outActionCommand = new DelegateCommand<object>(ExecuteOutActionCommand));

        void ExecuteOutActionCommand(object obj)
        {
            try
            {
                byte output = (byte)(OUT[int.Parse(obj.ToString())] ? 1 : 0);
                si.co_motion_setDo(hMotion, int.Parse(obj.ToString()), output);
            }
            catch { }
        }

        public event Action<IDialogResult> RequestClose;

        public bool CanCloseDialog()
        {
            return true;
        }

        public void OnDialogClosed()
        {
            runFlag = false;

        }

        public void OnDialogOpened(IDialogParameters param)
        {
            hMotion = param.GetValue<IntPtr>("hMotion");
            runFlag = true;
            Run();
        }
        public IODialogViewModel()
        {
            for (int i = 0; i < 16; i++)
            {
                IN.Add(false);
                OUT.Add(false);
            }
        }
        private async void Run()
        {
            while (runFlag)
            {
                try
                {
                    for (int i = 0; i < 16; i++)
                    {
                        byte input = 0;
                        si.co_motion_getDi(hMotion, i, ref input);
                        IN[i] = input == 1;

                        byte output = 0;
                        si.co_motion_getDo(hMotion, i, ref output);
                        OUT[i] = output == 1;
                    }

                }
                catch { }
                await Task.Delay(100);
            }
        }
    }
}
